class BizUnit < ActiveRecord::Base
  has_many :users

  validates :code, :presence => true, :uniqueness => true
  validates :name, :presence => true,
            :uniqueness => true,
            :length => {:minimum => 2, :maximum => 50}

  validates :longitude, :numericality => { :only_integer => true, :greater_than => 1000000}
  validates :latitude, :numericality => { :only_integer => true, :greater_than => 1000000}

  #错误信息提示
  def diy_error_msg(attr)
   "<span style='color:red'>" + ( self.errors[attr].join ',' ) + "</span>"
  end


  def to_s
    "#{code}:#{name}"
  end

  # 将报文数据保存在临时文件中
  def datagram_save(datagram, code)

    #当前日期
    date = Time.new.strftime("%Y%m%d")
    path = '/tmp'
    if !(File.exist? "#{path}/datagram")
      Dir.mkdir "#{path}/datagram"
    end
    if !(File.exist? "#{path}/datagram/#{date}")
      Dir.mkdir "#{path}/datagram/#{date}"
    end
    logger.debug "self.class:#{self.class}--#{self.class.to_s}"
    real_caller = self.class.to_s
    if !(File.exist? "#{path}/datagram/#{date}/#{real_caller}")
      Dir.mkdir "#{path}/datagram/#{date}/#{real_caller}"
    end
    if !(File.exist? "#{path}/datagram/#{date}/#{real_caller}/#{real_caller}_#{code}_#{date}.txt")
      f = File.new("#{path}/datagram/#{date}/#{real_caller}/#{real_caller}_#{code}_#{date}.txt", "a")
    else
      f = File.open("#{path}/datagram/#{date}/#{real_caller}/#{real_caller}_#{code}_#{date}.txt", "a")
    end
    f.puts("time:#{Time.now}--datagram:#{datagram}")
    f.close
  end

#校验报文
  def check_datagram?(datagram)
    #子类去实现
    false
  end

#报文解析
  def read_datagram(datagram)
    logger.debug "read_datagram"
    logger.debug check_datagram?(datagram)
    if check_datagram?(datagram)
      #TODO子类实现
    end
  end
end
